<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/12/11
 * Time: 17:21
 */

namespace app\storage\controller;

use app\storage\model\RoleModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Request;

class RoleController extends AdminBaseController
{
    private $roleModel;

    public function __construct(RoleModel $roleModel, Request $request = null)
    {
        parent::__construct($request);
        $this->roleModel = $roleModel;
    }

    public function index()
    {
        return $this->fetch('index');
    }

    public function add()
    {
        $role = $this->roleModel->select();
        $this->assign('role', $role);
        return $this->fetch('add');
    }

    public function edit()
    {
        $id = input('id');
        $role = $this->roleModel->where('id', $id)->find();
        $this->assign('role', $role);
        return $this->fetch('edit');
    }

    public function getRole()
    {
        $result = $this->roleModel->alias('a')
            ->join("(select id,name as parent_name from cmf_role) as b", 'a.parent_id = b.id', 'left')
            ->field('a.*,b.parent_name')
            ->select();
        return json($result);
    }

    public function addRole()
    {
        $param = input();
        $param['time'] = get_current_time();
        $this->roleModel->insert($param);
        $this->redirect('Role/index');
    }

    /**
     *
     */
    public function deleteRole()
    {
        $id = input('id');
        Db::startTrans();
        $result1 = Db::table('cmf_role')->where('id', $id)->delete();
        $result2 = Db::table('cmf_role_user')->where('role_id', $id)->update(['role_id'=>'']);
        if ($result1 && $result2 !== false) {
            Db::commit();
            ajax_response(true,'删除成功');
        } else {
            Db::rollback();
            ajax_response(false,'删除失败');
        }
    }


    public function editRole()
    {
        $data = input();
        $this->roleModel->isUpdate(true)->save($data);
        $this->redirect('Role/index');
    }

    public function checkRoleName()
    {
        $id = input('id');
        $whereAnd = empty($id) ? '' : " and id != '$id'";
        $where = sprintf("binary name = '%s' $whereAnd", input('name'));
        $repeat = $this->roleModel->where($where)->find();
        return boolval($repeat);
    }

}